package com.stefan.service.impl;

import com.github.benmanes.caffeine.cache.Cache;
import com.stefan.entity.User;
import com.stefan.service.UserService;
import com.stefan.util.RedisOpsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class UserServiceImpl implements UserService {
    @Autowired
    private Cache<String, User> userCache;
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private RedisOpsUtil redisOpsUtil;
    @Override
    public void addUser(String name, String email) {
        String sql = "INSERT INTO user (name, email) VALUES (?, ?)";
        int update = jdbcTemplate.update(sql, name, email);
        if (update>0) {
            sql = "SELECT id,name,email FROM user WHERE name = ?";
            User user = jdbcTemplate.queryForObject(sql, (rs,num) -> {
                return new User(rs.getInt("id"), rs.getString("name"), rs.getString("email"));
            }, name);
            // 将用户信息存入Redis
            redisOpsUtil.set(name, user);
        }
    }

    @Override
    public void deleteUser(String name) {

    }

    @Override
    public User getUser(String name) {
        //从caffeine缓存中获取用户信息
        User user= userCache.getIfPresent(name);
        if (user != null) {
            System.out.println("从Caffeine缓存中获取用户信息: " + user);
            return user;
        }
        user = redisOpsUtil.get(name, User.class);
        if (user != null) {
            System.out.println("从Redis缓存中获取用户信息: " + user);
            // 将用户信息存入Caffeine缓存
            userCache.put(name, user);
        }
        return user;
    }

    @Override
    public void updateUser(String name, String email) {

    }

    @Override
    public void preHeatCache() {
        // 从redis中获取用户数据 - 有待实现
//        redisTemplate.opsForValue().get()
//        userCache.put(userCacheName, range);
    }
}
